package fun._6742.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;
import fun._6742.interceptor.LoginInterceptor;
import fun._6742.mapper.UserMapper;
import fun._6742.model.dataobject.UserDO;
import fun._6742.model.valueobject.LoginUser;
import fun._6742.service.FileService;
import fun._6742.utils.oss.MinioTemplate;

import javax.annotation.Resource;

@Slf4j
@Service
public class FileServiceImpl implements FileService {

    @Resource
    MinioTemplate minioTemplate;

    @Resource
    UserMapper userMapper;

    @Override
    public void uploadUserHeadImg(String url) {
        LoginUser loginUser = LoginInterceptor.threadLocal.get();

        // 查找旧文件路径并删除
        UserDO userDO = userMapper.selectById(loginUser.getId());

        String oldUrl = userDO.getHeadImg();
        if (oldUrl != null) {
            minioTemplate.removeObject(oldUrl);
        }

        // 设置新路径并保存
        userDO.setHeadImg(url);
        userMapper.updateById(userDO);

        log.info("update headImg success, user: {}", loginUser.getId());
    }
}
